﻿using System;
using System.Web;
using System.Web.Script.Serialization;
using IapApp;
using IapApp.Manager;
using IapApp.Security;

namespace IapService.Service
{
    public class Service
    {
        public const string JOB_SAVE = "save";
        public const string JOB_REMOVE = "remove";

        protected ServiceResponse<T> Execute<T>(Func<T> action)
            where T : new()
        {
            var response = new ServiceResponse<T>();
            try
            {
                if(AppGlobal.CheckSecuritySession)
                    SessionManager.VerifySession();
                response.Result = action();
            }
            catch (SessionException exception)
            {
                response.Status.Message = exception.Message;
                response.Status.Code = StatusCode.SESSION_END;
            }
            catch (Exception exception)
            {
                response.Status.Message = exception.Message;
                response.Status.Code = StatusCode.ERROR;
            }
            return response;
        }

        private static T JsonDeserialize<T>(string jsonString)
        {
            var ser = new JavaScriptSerializer();
            return ser.Deserialize<T>(jsonString);
        }

        protected static T TranslateFromPost<T>()
        {
            var jsonString = HttpContext.Current.Request.Form["main"];
            return JsonDeserialize<T>(jsonString);
        }
    }
}